package bat.iog.hytool.convert;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

/**
 * byte类型占用1个字节，
 */
public class ByteUtils {
    
    private static final char HexCharArr[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};

    public static void main(String[] args) {
        byteArrToHex(heartbeat());
        System.out.println(byteArrToHex(heartbeat()));
        byte[] bytes = new byte[8];
        intToByteArray(-128,bytes,0);
        System.out.println(bytes[0]);
        System.out.println(bytes[1]);
        System.out.println(bytes[2]);
        System.out.println(bytes[3]);
        System.out.println(bytes[4]);
        System.out.println(bytes[5]);
        System.out.println(bytes[6]);
        System.out.println(bytes[7]);
    }
    
   static byte[] heartbeat() {
        byte[] bytes = new byte[8];
        intToByteArray(-128, bytes, 0);
        intToByteArray(0, bytes, 4);
        return bytes;
   }

   /**
    * int占4个字节，byte占1个字节；
    * int a = -128，转换成⼆进制形式是1000 0000 0000 0000 0000 0000 1000 0000
    * --------------------------------------------------------
    * 将int装换为byte数组
    * @param i 需要装换的int数据
    * @param bytes 存放装换后的byte数组
    * @param index byte数组的下标
    */
   private static void intToByteArray(int i, byte[] bytes, int index) {
       bytes[index++] = (byte) ((i >> 24) & 0xFF);
       bytes[index++] = (byte) ((i >> 16) & 0xFF);
       bytes[index++] = (byte) ((i >> 8) & 0xFF);
       bytes[index] = (byte) (i & 0xFF);
   }

   private void intToByteArrayValue(int i, byte[] bytes, int index) {
       bytes[index++] = (byte) ((i) & 0xFF);
       bytes[index++] = (byte) ((i >> 8) & 0xFF);
       bytes[index++] = (byte) ((i >> 16) & 0xFF);
       bytes[index] = (byte) (i >> 24 & 0xFF);
   }
   
   /**
    * 将byte[]转换为十六进制字符串
    */
   public static String byteArrToHex(byte[] btArr) {
       char strArr[] = new char[btArr.length * 2];
       int i = 0;
       for (byte bt : btArr) {
           strArr[i++] = HexCharArr[bt >>> 4 & 0xf];
           strArr[i++] = HexCharArr[bt & 0xf];
       }
       return new String(strArr);
   }
   
}
